/**
 * 
 */
package de.idgard.android.addon.ui.services.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import de.idgard.android.R;
import de.idgard.android.addon.services.ContextAware;
import de.idgard.android.addon.ui.services.JavaScriptLoaderService;

/**
 * 
 * @author <a href="mailto:vesko.georgiev@uniscon.com">Vesko Georgiev</a>
 */
public class JavaScriptLoaderImpl implements JavaScriptLoaderService, ContextAware {

	private Context context;
	private Map<Object, String> scripts = new HashMap<Object, String>();

	@Override
	public void setContext(Context ctx) {
		this.context = ctx;
	}

	private String read(InputStream is) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			StringBuilder builder = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				if (line.length() > 0  && !line.startsWith("//")) {
					builder.append(line).append("\n");
				}
			}
			return builder.toString();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			if (reader != null) {
				try {
					reader.close();
				}
				catch (IOException e) {
					//
				}
			}
		}
		return null;
	}

	@SuppressWarnings("unused")
	private String getJQueryScript() {
		try {
			String url = "http://code.jquery.com/jquery-1.7.2.js";
			String script = scripts.get(url);
			if (script == null) {
				scripts.put(url, script = read(new URL(url).openStream()));
			}
			return script;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private String getScript(int resId) {
		try {
			String script = scripts.get(resId);
			if (script == null) {
				scripts.put(resId, script = read(context.getResources().openRawResource(resId)));
			}
	        return script; 
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private int getResourceId(String script) {
		try {
			return (Integer) R.raw.class.getDeclaredField(script.replace(".js", "")).get(null);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return -1;
	}

	private String doImports(String script) {
		Pattern p = Pattern.compile("(\\{\\{ import:(.*?) \\}\\})", Pattern.MULTILINE);
		Matcher m = p.matcher(script);

		while (m.find()) {
			String toReplace = m.group();
			String importScript = m.group(m.groupCount());

			int resId = getResourceId(importScript);
			if (resId > 0) {
				String imported = getScript(resId);
				script = script.replace(toReplace, imported);
			}
		}
		return script;
	}

	private String getWrappedScript(int resId) {
		String script = getScript(resId);
		script = doImports(script);
		return "javascript: (function() {" + script + "})();";
	}

	public String getPrivacyConnectScript() {
		return getWrappedScript(R.raw.privacy_connect);
	}

	public String getOneClickLoginListenerScript() {
		return getWrappedScript(R.raw.one_click_login_listener);
	}
	
}
